import { reloadAuthorized } from './Authorized';



export function getAuthority(str) {
  const authorityString =
    // typeof str === 'undefined' && sessionStorage ? sessionStorage.getItem('authority') : str;
    typeof str === 'undefined' && getCookie('authority') !== 'undefined' ? getCookie('authority') : str;
    // typeof str === 'undefined' && localStorage ? localStorage.getItem('authority') : str; // authorityString could be admin, "admin", ["admin"]

  let authority;

  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }

  if (typeof authority === 'string') {
    return [authority];
  } // preview.pro.ant.design only do not use in your production.
  // preview.pro.ant.design 专用环境变量，请不要在你的项目中使用它。

  if (!authority && ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return ['guest'];
  }
  return authority;
}
export function setAuthority(authority) {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;

  // localStorage.setItem('authority', JSON.stringify(proAuthority)); // auto reload
  //    sessionStorage.setItem('authority', JSON.stringify(proAuthority)); // auto reload
  setCookie('authority', JSON.stringify(proAuthority));
  reloadAuthorized();
}

export function setCookie(c_name,value) {
  const expire = 3600;
  const date = new Date();
  date.setSeconds(date.getSeconds()+expire);
  document.cookie=`${c_name }=${escape(value)}; expires=${date.toGMTString()}; path=/`
}


export function getCookie(c_name){
  if (document.cookie.length>0){
    // eslint-disable-next-line @typescript-eslint/naming-convention
    let c_start=document.cookie.indexOf(`${c_name  }=`);
    if (c_start!==-1){
      c_start=c_start + c_name.length+1;
      // eslint-disable-next-line @typescript-eslint/naming-convention
      let c_end=document.cookie.indexOf(";",c_start);
      if (c_end===-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end))
    }
  }
  return ""
}

export function delCookie(c_name){
  setCookie(c_name, "", -1)
}
